package com.canlihao.ui.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.canlihao.ui.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import butterknife.BindView;
import butterknife.ButterKnife;

/*******
 *
 *Created by panda李
 *
 *创建时间 2020/2/10
 *
 *类描述：
 *
 ********/
public class UpdateDialog extends Dialog {
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.apk_name)
    TextView apkName;
    @BindView(R.id.tv_progress)
    TextView tvProgress;
    @BindView(R.id.progressbar)
    ProgressBar progressbar;
    @BindView(R.id.ll_progress)
    LinearLayout llProgress;
    @BindView(R.id.btnoff)
    Button btnoff;
    @BindView(R.id.btnon)
    Button btnon;
    Activity context;
    String desc = "",url = "",force = "";
    String apkPath;
    String apkNameString;
    String stringVal = "";
    int numpro = 0;
    private boolean canceled = false;
    MyHandler myHandler;
    class DownApkRunnable implements Runnable {

        @Override
        public void run() {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    downloadApk();
                }
            });
        }

    }
    private int laterate = 0;
    private void downloadApk() {
        try {
            URL url = new URL(stringVal);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            int length = conn.getContentLength();
            int count = 0;
            File apkPathFile = new File(apkPath);
            if (!apkPathFile.exists()) {
                apkPathFile.mkdir();
            }
            conn.connect();
            File apkFile = new File(apkPath, apkNameString);
            InputStream in = conn.getInputStream();
            FileOutputStream os = new FileOutputStream(apkFile);
            byte[] buffer = new byte[1024];
            do {
                int numread = in.read(buffer);
                count += numread;
                int progress = (int) (((float) count / length) * 100);// 得到当前进度
                if (progress >= laterate + 1) {// 只有当前进度比上一次进度大于等于1，才可以更新进度
                    laterate = progress;
                    Message msg = new Message();
                    msg.what = 1;
                    msg.arg1 = progress;
                    //handler.sendMessage(msg);
                    myHandler.sendMessage(msg);
                }
                if (numread <= 0) {// 下载完毕
                    //handler.sendEmptyMessage(2);
                    myHandler.sendEmptyMessage(2);
                    canceled = true;
                    break;
                }
                os.write(buffer, 0, numread);
            } while (!canceled);// 如果没有被取消
            in.close();
            os.close();
        } catch (MalformedURLException e) {
            ToastUtil.showToast(context,"下载出错了，请重试");
            btnon.setText("重试");
            btnoff.setVisibility(View.VISIBLE);
            e.printStackTrace();
        } catch (IOException e) {
            ToastUtil.showToast(context,"下载出错了，请重试");
            btnon.setText("重试");
            btnoff.setVisibility(View.VISIBLE);
            e.toString();
            e.printStackTrace();
        }

    }
    /* 创建静态内部类
     */
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(context!=null){
                //执行业务逻辑
                switch (msg.what) {
                    case 1:// 更新进度
                        int progress = msg.arg1;
                        numpro = progress;
                        if (progress < 100) {
                            apkName.setText("Li");
                            tvProgress.setText(progress + "%");
                            progressbar.setProgress(progress);
                        } else {// 下载完成，停止服务
                            tvProgress.setText(progress + "%");
                            progressbar.setProgress(progress);
                            apkName.setText("Li");
                            if(force.equals("1")){
                                btnoff.setVisibility(View.GONE);
                            }else{
                                btnoff.setVisibility(View.VISIBLE);
                            }
                            btnon.setText("安装");
                        }
                        break;
                    case 2:// 安装apk
                        ToastUtil.showToast(context,"下载完成，请点击安装");
                        installApk();
                        break;

                    default:
                        break;
                }
            }
        }
    }
    /**
     * 安装apk
     */
    private void installApk() {
        File file = new File(apkPath,apkNameString);

        Intent intent = new Intent();

        intent.setAction(Intent.ACTION_VIEW);

        if (Build.VERSION.SDK_INT >= 24)

        { // Android7.0及以上版本 Log.d("-->最新apk下载完毕","Android N及以上版本");

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            Uri contentUri = FileProvider.getUriForFile(context, "com.canlihao.ui.FileProvider", file);

//参数二:应用包名+".fileProvider"(和步骤二中的Manifest文件中的provider节点下的authorities对应)

            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

        } else {

// Android7.0以下版本 Log.d("-->最新apk下载完毕","Android N以下版本");

            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);}

        context.startActivity(intent);

    }
    public UpdateDialog(Activity context,String desc,String url,String force) {
        super(context);
        this.context = context;
        this.desc = desc;
        this.stringVal = url;
        this.force = force;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_update);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        if(force.equals("1")){
            btnoff.setVisibility(View.GONE);
        }else{
            btnoff.setVisibility(View.VISIBLE);
        }
        btnon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(btnon.getText().toString().equals("下载") || btnon.getText().toString().equals("重试")){
                    btnoff.setVisibility(View.GONE);
                    btnon.setText("下载中");
                    llProgress.setVisibility(View.VISIBLE);
                    new Thread(new DownApkRunnable()).start();
                }else if(btnon.getText().toString().equals("安装")){
                    installApk();
                }
            }
        });
        tvContent.setText(desc);
        update();
        btnoff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
    }
    public void update(){
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            apkPath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath();
            apkNameString = "li_test.apk";
            //registerBroader();
            myHandler = new MyHandler();
            //new Thread(new DownApkRunnable()).start();
        } else {
            Toast.makeText(context, "SD卡不存在", Toast.LENGTH_SHORT)
                    .show();
        }
    }
    public void dialogShow(){
        show();
    }
    public void dialogDismiss(){
        dismiss();
    }
}
